<?php
declare (strict_types=1);

namespace app\store\model\questionnaire;

use app\common\model\questionnaire\Questionnaire as QuestionnaireModel;
use app\store\model\UploadFile;
use think\db\exception\DbException;
use think\Paginator;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Questionnaire extends QuestionnaireModel
{
    /**
     * 获取用户列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        $order = [
            'create_time' => 'desc',
        ];
        if (!empty($param['create_time']) && is_array($param['create_time'])) {
            $times = between_time($param['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        } else if (!empty($param['create_time'])) {
            $order['create_time'] = $param['create_time'];
        }

        if (!empty($param['update_time']) && is_array($param['update_time'])) {
            $times = between_time($param['update_time']);
            $filter[] = ['update_time', '>=', $times['start_time']];
            $filter[] = ['update_time', '<', $times['end_time'] + 86400];
        } else if (!empty($param['update_time'])) {
            $order['update_time'] = $param['update_time'];
        }


        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order($order)
            ->paginate($param['pageSize'] ?? 10);
        return $list;
    }

    public function getAllList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc',])
            ->select();
        return $list;
    }


    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'search' => '',
            'questionnaire_name' => '',
            'status' => '',
        ]);

        $filter = [];
        !empty($params['search']) && $filter[] = ["subject_name", "like", "%{$params['search']}%"];
        !empty($params['questionnaire_name']) && $filter[] = ["questionnaire_name", "like", "%{$params['questionnaire_name']}%"];
        $params['status'] !== '' && $filter[] = ['status', '=', $params['status']];
        return $filter;
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data)
    {
        $this->transaction(function () use ($data) {
            $data['store_id'] = self::$storeId;
            $this->save($data);

            if (!empty($data['topic_import_file_id'])) {
                $fileInfo = UploadFile::detail((int)$data['topic_import_file_id']);
                $filePath = ROOT_PATH() . '/public/uploads/' . $fileInfo->file_path;
                $spreadsheet = IOFactory::load($filePath);
                $list = $spreadsheet->getActiveSheet()->toArray();
                $addData = [];

                //大写字母
                $uppercaseLetters = array_map('chr', range(65, 90));

                foreach ($list as $index => $item) {
                    $arr = [
                        'questionnaire_id' => $this->questionnaire_id,
                        'create_time' => time(),
                        'store_id' => self::$storeId,
                    ];
                    if ($index > 0 && count(array_filter($item)) > 0) {
                        // 标题
                        if (empty($item[0])) {
                            $error = "第" . ($index + 1) . "行题目标题不能为空！";
                            throwError($error);
                        } else {
                            $arr['title'] = trim($item[0]);
                        }

                        // 题目类型
                        if (empty($item[1])) {
                            $error = "第" . ($index + 1) . "行题目类型不能为空！";
                            throwError($error);
                        } else {
                            $types = [
                                '单选题' => 0,
                                '多选题' => 1,
                                '判断题' => 2,
                            ];
                            $type = trim($item[1]);
                            if (!isset($types[$type])) {
                                $error = "第" . ($index + 1) . "行题目类型不规范！";
                                throwError($error);
                            }
                            $arr['topic_type'] = $types[$type];
                        }

                        // 计分方式
                        $arr['scoring_method'] = 1;

                        // 分数
                        if (empty($item[3])) {
                            $error = "第" . ($index + 1) . "行分数不能为空！";
                            throwError($error);
                        } else {
                            $arr['fraction'] = (int)$item[3];
                        }

                        //正确答案
                        if (empty($item[4])) {
                            $error = "第" . ($index + 1) . "行分数不能为空！";
                            throwError($error);
                        } else {
                            $arr['correct_answer'] = trim($item[4]);
                        }

                        $index = 0;
                        $arr['items'] = [];
                        for ($i = 5; $i <= 13; $i++) {
                            if (!empty($item[$i])) {
                                $arr['items'][] = [
                                    'option' => $uppercaseLetters[$index],
                                    'text' => $item[$i],
                                ];
                                $index++;
                            }
                        }
                        $arr['items'] = json_encode($arr['items'], 320);
                        $addData[] = $arr;
                    }
                }
                (new Topic())->insertAll($addData);
            }
        });
        return true;
    }

    public function add2($data)
    {
        if (self::checkQuestionnaireNameExist($data['questionnaire_name'])) {
            $this->error = $data['questionnaire_name'] . '已存在，请换一个重试！';
            return false;
        }

        $this->transaction(function () use ($data) {
            $data['store_id'] = self::$storeId;
            $this->save($data);

            if (!empty($data['topic_import_file_id'])) {
                $fileInfo = UploadFile::detail((int)$data['topic_import_file_id']);
                $filePath = ROOT_PATH() . '/public/uploads/' . $fileInfo->file_path;
                $spreadsheet = IOFactory::load($filePath);
                $list = $spreadsheet->getActiveSheet()->toArray();
                $addData = [];

                //大写字母
                $uppercaseLetters = array_map('chr', range(65, 90));

                foreach ($list as $index => $item) {
                    $arr = [
                        'questionnaire_id' => $this->questionnaire_id,
                        'create_time' => time(),
                        'store_id' => self::$storeId,
                    ];
                    if ($index > 0 && count(array_filter($item)) > 0) {

                        // 题目类型
                        if (empty($item[1])) {
                            $error = "第" . ($index + 1) . "行题目类型不能为空！";
                            throwError($error);
                        } else {
                            $types = [
                                '选择题' => 0,
                                '单选题' => 0,
                                '多选题' => 1,
                                '判断题' => 2,
                            ];
                            $type = trim($item[1]);
                            if (!isset($types[$type])) {
                                $error = "第" . ($index + 1) . "行题目类型不规范！";
                                throwError($error);
                            }
                            $arr['topic_type'] = $types[$type];
                        }

                        // 标题
                        if (empty($item[2])) {
                            $error = "第" . ($index + 1) . "行题目标题不能为空！";
                            throwError($error);
                        } else {
                            $arr['title'] = trim($item[2]);
                        }

                        $index = 0;
                        $arr['items'] = [];
                        for ($i = 3; $i <= 6; $i++) {
                            if (!empty($item[$i])) {
                                $arr['items'][] = [
                                    'option' => $uppercaseLetters[$index],
                                    'text' => $item[$i],
                                ];
                                $index++;
                            }
                        }
                        $arr['items'] = json_encode($arr['items'], 320);

                        // 计分方式
                        $arr['scoring_method'] = 1;

                        // 分数
//                        if (empty($item[3])) {
//                            $error = "第" . ($index + 1) . "行分数不能为空！";
//                            throwError($error);
//                        } else {
                        $arr['fraction'] = 2;
//                        }

                        //正确答案
                        if (empty($item[7])) {
                            $error = "第" . ($index + 1) . "行正确答案不能为空！";
                            throwError($error);
                        } else {
                            $correct_answer = trim($item[7]);
                            if ($arr['topic_type'] === 2) {
                                $as = [
                                    '正确' => 'A',
                                    '错误' => 'B',
                                    '✓' => 'A',
                                    '√' => 'A',
                                    '×' => 'B',
                                    'A' => 'A',
                                    'B' => 'B',
                                ];
                                if(empty($as[$correct_answer])){
                                    $error = "第" . ($index + 1) . "行正确答案格式错误！";
                                    throwError($error);
                                }
                                $arr['correct_answer'] = $as[$correct_answer] ?? $correct_answer;
                            } else {
                                $arr['correct_answer'] = $correct_answer;
                            }
                        }

                        //解析
                        if (!empty($item[8])) {
                            $arr['analysis'] = trim($item[8]);
                        }

                        $addData[] = $arr;
                    }
                }
                (new Topic())->insertAll($addData);
            }
        });
        return true;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        if ($data['questionnaire_name'] != $this->questionnaire_name && self::checkQuestionnaireNameExist($data['questionnaire_name'])) {
            $this->error = $data['questionnaire_name'] . '已存在，请换一个重试！';
            return false;
        }

        $this->transaction(function () use ($data) {
            $this->save($data);
            if (!empty($data['topic_import_file_id'])) {
                $fileInfo = UploadFile::detail((int)$data['topic_import_file_id']);
                $filePath = ROOT_PATH() . '/public/uploads/' . $fileInfo->file_path;
                $spreadsheet = IOFactory::load($filePath);
                $list = $spreadsheet->getActiveSheet()->toArray();
                $addData = [];

                //大写字母
                $uppercaseLetters = array_map('chr', range(65, 90));

                foreach ($list as $index => $item) {
                    $arr = [
                        'questionnaire_id' => $this->questionnaire_id,
                        'create_time' => time(),
                        'store_id' => self::$storeId,
                    ];
                    if ($index > 0 && count(array_filter($item)) > 0) {

                        // 题目类型
                        if (empty($item[1])) {
                            $error = "第" . ($index + 1) . "行题目类型不能为空！";
                            throwError($error);
                        } else {
                            $types = [
                                '选择题' => 0,
                                '单选题' => 0,
                                '多选题' => 1,
                                '判断题' => 2,
                            ];
                            $type = trim($item[1]);
                            if (!isset($types[$type])) {
                                $error = "第" . ($index + 1) . "行题目类型不规范！";
                                throwError($error);
                            }
                            $arr['topic_type'] = $types[$type];
                        }

                        // 标题
                        if (empty($item[2])) {
                            $error = "第" . ($index + 1) . "行题目标题不能为空！";
                            throwError($error);
                        } else {
                            $arr['title'] = trim($item[2]);
                        }

                        $index = 0;
                        $arr['items'] = [];
                        for ($i = 3; $i <= 6; $i++) {
                            if (!empty($item[$i])) {
                                $arr['items'][] = [
                                    'option' => $uppercaseLetters[$index],
                                    'text' => $item[$i],
                                ];
                                $index++;
                            }
                        }
                        $arr['items'] = json_encode($arr['items'], 320);

                        // 计分方式
                        $arr['scoring_method'] = 1;

                        // 分数
//                        if (empty($item[3])) {
//                            $error = "第" . ($index + 1) . "行分数不能为空！";
//                            throwError($error);
//                        } else {
                        $arr['fraction'] = 2;
//                        }

                        //正确答案
                        if (empty($item[7])) {
                            $error = "第" . ($index + 1) . "行正确答案不能为空！";
                            throwError($error);
                        } else {
                            $correct_answer = trim($item[7]);
                            if ($arr['topic_type'] === 2) {
                                $as = [
                                    '正确' => 'A',
                                    '错误' => 'B',
                                    '✓' => 'A',
                                    '√' => 'A',
                                    '×' => 'B',
                                    'A' => 'A',
                                    'B' => 'B',
                                ];
                                if(empty($as[$correct_answer])){
                                    $error = "第" . ($index + 1) . "行正确答案格式错误！";
                                    throwError($error);
                                }
                                $arr['correct_answer'] = $as[$correct_answer] ?? $correct_answer;
                            } else {
                                $arr['correct_answer'] = $correct_answer;
                            }
                        }

                        //解析
                        if (!empty($item[8])) {
                            $arr['analysis'] = trim($item[8]);
                        }

                        $addData[] = $arr;
                    }
                }
                (new Topic())->insertAll($addData);
            }
        });

        return $this->save($data);
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }


}
